import { CacheEnum } from "@/enum/cacheEnum";
import store from "./store";
import userApi from "@/apis/userApi";
import router from "@/router";
import type { IloginData } from "@/apis/userApi";
import { useUserStore } from "@/store/userStore";

export async function login(values: IloginData) {
  const {
    result: { token, user },
    message,
    code,
  } = await userApi.login(values);
  switch (code) {
    case 200:
      //将token存入Localstorage
      store.set(
        CacheEnum.TOKEN_NAME,
        {
          token: token,
          userInfo: user,
        },
        12 * 60 * 60
      );
      //将用户信息存入pinia
      useUserStore().getUserInfo(user);
      //跳转到登录之前访问的页面,如果没有就返回home
      const routeName = store.get(CacheEnum.REDIRECT_ROUTE_NAME) ?? "home";
      router.push({ name: routeName });
      break;
    case 300:
      alert(message);
      break;
    default:
      break;
  }
}

export function logout() {
  store.remove(CacheEnum.TOKEN_NAME);
  router.push({ name: "login" });
  useUserStore().info = null;
}
